package com.swz.dcrm.ui.home;


import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.swz.dcrm.adpter.DeliveryCarAdapter;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.adpter.TodayPlanAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.Clue;
import com.swz.dcrm.model.ClueDetail;
import com.swz.dcrm.model.ClueRecord;
import com.swz.dcrm.model.DeliveryCar;
import com.swz.dcrm.model.Page;
import com.swz.dcrm.model.VisitRecord;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import android.view.ViewTreeObserver;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.MainViewModel;
import com.swz.dcrm.ui.viewmodel.TodayPlanViewModel;
import com.swz.dcrm.util.CustomDecoration;
import com.swz.dcrm.widget.NearlySenvenDayView;
import com.swz.dcrm.wrapper.EmptyWrapper;
import com.xh.baselibrary.callback.OnClickListener;


import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class NearlyDeliveryFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.nearlySenvenDayView)
    NearlySenvenDayView senvenDayView;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.rv)
    RecyclerView rv;
    private DeliveryCarAdapter deliveryCarAdapter;


    int page=1;
    int size=10;
    int total;
    ValueAnimator valueAnimator;
    int height;
    @Inject
    TodayPlanViewModel todayPlanViewModel;
    @Inject
    MainViewModel mainViewModel;
    private EmptyWrapper emptyWrapper;

    public static NearlyDeliveryFragment newInstance() {

        return new NearlyDeliveryFragment();
        // Required empty public constructor
    }
    @Override
    public void onLoadRetry() {
        if(!isNetworkConnected(getContext())){
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }
        mHolder.showLoading();
        todayPlanViewModel.getNearlyDeliveryCount()
                .observe(this, listBaseResponse -> {
                    mHolder.showLoadSuccess();
                    if(listBaseResponse.isSuccess()){
                        senvenDayView.setData(listBaseResponse.getData());
                        senvenDayView.click();
                    }
                });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        height=senvenDayView.getMeasuredHeight();
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_nearly_delivery;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        title.setText(getResources().getString(R.string.nearly_delivery_title));
        smartRefreshLayout.setEnableRefresh(false);
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        rv.addItemDecoration(new CustomDecoration(getContext(),0,10,10,10));

        smartRefreshLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                smartRefreshLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                height=senvenDayView.getHeight();
                rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                        super.onScrollStateChanged(recyclerView, newState);
                    }

                    @Override
                    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {


                        Log.i("smartRefreshLayout","dy="+dy+",height="+height);
                        if(recyclerView.computeVerticalScrollOffset()>height){
                            title.setText(senvenDayView.getCurrentText());
                            if(senvenDayView.getHeight()==0||(valueAnimator!=null&&valueAnimator.isRunning())){
                                return;
                            }
                            valueAnimator=ValueAnimator.ofInt(senvenDayView.getHeight(),0);
                            valueAnimator.addUpdateListener(animation -> {
                                ViewGroup.LayoutParams layoutParams=senvenDayView.getLayoutParams();
                                layoutParams.height= (int) animation.getAnimatedValue();
                                senvenDayView.setLayoutParams(layoutParams);
                            });
                            valueAnimator.setDuration(100);
                            valueAnimator.start();
                        }else {
                            title.setText(getString(R.string.nearly_delivery_title));
                            if(senvenDayView.getHeight()==height||(valueAnimator!=null&&valueAnimator.isRunning())){
                                return;
                            }
                            valueAnimator=ValueAnimator.ofInt(0,height);
                            valueAnimator.addUpdateListener(animation -> {
                                ViewGroup.LayoutParams layoutParams=senvenDayView.getLayoutParams();
                                layoutParams.height= (int) animation.getAnimatedValue();
                                senvenDayView.setLayoutParams(layoutParams);
                            });
                            valueAnimator.setDuration(100);
                            valueAnimator.start();
                        }
                    }
                });
            }
        });

        senvenDayView.setOnItemClickListener(s -> {
            page=1;
            if(deliveryCarAdapter!=null){
                deliveryCarAdapter.clear();
            }
            smartRefreshLayout.setEnableLoadmore(true);
            todayPlanViewModel.getNearlyDelivery(s,page,size)
                    .observe(this, observer);
        });

        smartRefreshLayout.setOnLoadmoreListener(refreshlayout -> {
            if(deliveryCarAdapter!=null&&deliveryCarAdapter.getItemCount()>=total){
                smartRefreshLayout.finishLoadmore();
                smartRefreshLayout.setEnableLoadmore(false);
                return;
            }else {
                page++;
                onLoadRetry();
            }
        });
        return true;
    }

    Observer<BaseResponse<Page<DeliveryCar>>>observer=new Observer<BaseResponse<Page<DeliveryCar>>>() {
        @Override
        public void onChanged(BaseResponse<Page<DeliveryCar>> pageBaseResponse) {
            if(pageBaseResponse.isSuccess()){
                smartRefreshLayout.finishLoadmore();
                total=pageBaseResponse.getData().getTotal();
                if(deliveryCarAdapter==null){

                    deliveryCarAdapter=new DeliveryCarAdapter(getContext(),pageBaseResponse.getData().getList());
                    deliveryCarAdapter.setOnClickListener(onClickListener);
                    deliveryCarAdapter.setOnButtonClick(onButtonClick);
                    emptyWrapper=getEmptyWrapper(deliveryCarAdapter,R.mipmap.empty_task);
                    rv.setAdapter(emptyWrapper);
                }else {
                    deliveryCarAdapter.refresh(pageBaseResponse.getData().getPageNum(),pageBaseResponse.getData().getList());
                    emptyWrapper.notifyDataSetChanged();
                }
            }
        }
    };


    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }
    private OnClickListener<DeliveryCar> onClickListener= deliveryCar -> {
        ClueDetailFragmentArgs.Builder builder=new ClueDetailFragmentArgs.Builder();
        builder.setClueId(new Gson().toJson(deliveryCar.getClueRecord().getBsClueVO().getId()));
        go(null,R.id.action_nearlyDeliveryFragment_to_clueDetailFragment,builder.build().toBundle());
    };
    private TodayPlanAdapter.OnButtonClick onButtonClick=new TodayPlanAdapter.OnButtonClick() {

        @Override
        public void onLogging(ClueRecord clueRecord) {
            AddVisitRecordFragmentArgs.Builder builder=new AddVisitRecordFragmentArgs.Builder();
            builder.setClueRecord(new Gson().toJson(clueRecord));
            go(null,R.id.action_nearlyDeliveryFragment_to_addVisitRecordFragment,builder.build().toBundle());
        }

        @Override
        public void onCall(String phone) {
            mainViewModel.getCall().setValue(phone);
        }

        @Override
        public void onHandUp(long clueId) {

        }
    };
}
